package com.wawei.seeds.champion;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wawei.seeds.R;
import com.wawei.seeds.comment.CommontListActivity;
import com.wawei.seeds.model.HeroInfo;
import com.wawei.seeds.model.WalnutMainEvent;
import com.wawei.seeds.services.WalnutMainServiceHandler;
import com.wawei.seeds.services.WalnutPortraitServiceHandler;
import com.wawei.seeds.utils.ImageAndAnimateUtils;
import com.wawei.seeds.utils.ImageLoader;
import com.wawei.seeds.utils.PrefUtils;
import com.wawei.seeds.utils.RetrofitNetworkService;
import com.wawei.seeds.utils.WalnutBaseNofityHandler;

import java.io.Serializable;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit.RestAdapter;

/**
 * Created by t27891 on 15/6/20.
 */
public class ChampionActivity extends ActionBarActivity {
    @InjectView(R.id.walnut_logo)ImageView logoImage;
    @InjectView(R.id.walnut_event_name)TextView eventName;
    @InjectView(R.id.walnut_event_image)ImageView eventImage;
    @InjectView(R.id.walnut_available_amount)TextView availableAmount;
    @InjectView(R.id.walnut_event_title)TextView eventTitle;
    @InjectView(R.id.walnut_event_action)TextView eventAction;

    @InjectView(R.id.walnut_event_detail)TextView eventDetail;
    @InjectView(R.id.walnut_event_value)TextView eventValue;
    @InjectView(R.id.walnut_hero_appointment)View appointmentView;
    @InjectView(R.id.submit_appointment)ImageView submitAppointmentImage;
    @InjectView(R.id.walnut_hero_appointment_status)TextView appointmentStatusView;

    @InjectView(R.id.walnut_hero_head)ImageView eventHeroHeadImage;
    @InjectView(R.id.walnut_hero_skill)TextView eventHeroSkill;
    @InjectView(R.id.walnut_hero_introduction)TextView eventHeroIntroduction;

    @InjectView(R.id.walnut_event_sharing)View eventSharing;

    @InjectView(R.id.walnut_hero_progress)View heroProgress;

    @InjectView(R.id.walnut_comment_service)View comment;

    private WalnutMainEvent event;
    private WalnutMainServiceHandler serviceHandler;
    private WalnutPortraitServiceHandler portraitServiceHandler;
    private ImageLoader imageLoader;
    private HeroNotifyHandler notifyHandler;

    //For getting publisher's info async
    public static final int GET_HERO_INFO = 0x01;

    //For getting champion event info async
    public static final int GET_EVENT_INFO = 0x02;

    // 预约事件消息类型
    public static final int RESERVATION_EVENT_INFO = 0x03;

    public static final int GET_BOOKING_STATE= 0x04;

    //For transferring the gotten item data. sometimes the item data has been downloaded before
    //opening ChampionActivity
    public static final String ITEM_DATA = "item";

    public static final String APPOINTMENT_STATUS_DONE = "已约";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_walnut_hero_detail);
        ButterKnife.inject(this);

        serviceHandler = new WalnutMainServiceHandler(this);
        portraitServiceHandler = new WalnutPortraitServiceHandler(this);
        imageLoader = new ImageLoader(this, R.drawable.event_placeholder);
        notifyHandler = new HeroNotifyHandler(this);

        Serializable serializable = getIntent().getSerializableExtra(ITEM_DATA);
        if(null == serializable){
            Toast.makeText(this, R.string.exception_no_data, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        else {
            event = (WalnutMainEvent)serializable;
            initChampionEvent(event.eventId, String.valueOf(PrefUtils.getUserId(this)));
            initHero(event.publisherId);

            initEventState(event, PrefUtils.getUserId(this));
            init(null);
        }
    }

    public void initEventState(WalnutMainEvent event, int userId) {
        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        serviceHandler.getBookingState(restAdapter, event, userId, notifyHandler, GET_BOOKING_STATE);
    }

    private void initChampionEvent(String itemId, String loggedIn){
        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        serviceHandler.retrieveEventDetail(restAdapter, itemId, loggedIn,
                notifyHandler, GET_EVENT_INFO);
    }
    
    private void initHero(String heroId){
        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        Bundle bundle = new Bundle();
        bundle.putInt(WalnutPortraitServiceHandler.PORTRAIT_WHO, Integer.valueOf((heroId == null || "".equals(heroId)) ? "0" : heroId));
        portraitServiceHandler.retrieveData(restAdapter, bundle, notifyHandler, GET_HERO_INFO);

        heroProgress.setVisibility(View.VISIBLE);
    }

    /**
     * Initialize the views
     * This activity is created by WalnutMainActivity, so the basic info of the event can be gotten from
     * the extra of intent. It has nice efficiency.
     */
    private void init(String state) {
        logoImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                finish();
            }
        });
        eventSharing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChampionActivity.this, ChampionMoreActivity.class);
                ChampionActivity.this.startActivity(intent);
            }
        });
        comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (event != null && event.publisherId != null) {
                    Intent intent = new Intent(ChampionActivity.this, ChampionCommentActivity.class);
                    intent.putExtra("providerId", event.publisherId);
                    ChampionActivity.this.startActivity(intent);
                } else {
                    Toast.makeText(ChampionActivity.this, "错误的发布者数据！", Toast.LENGTH_LONG).show();
                }
            }
        });

        if(null != event) {
            event.bookingState = state;
            initEvent();
        }
    }

    private void changeState(String state) {
        if(null != event) {
            event.bookingState = state;

            appointmentView.setVisibility(View.VISIBLE);
            if ("apply".equals(event.bookingState)) {
                submitAppointmentImage.setImageResource(R.drawable.grey_square);
                appointmentStatusView.setText(R.string.walnut_event_status_waiting);
                appointmentView.setOnClickListener(null);
            } else {
                submitAppointmentImage.setImageResource(R.drawable.red_square);
                appointmentStatusView.setText(R.string.walnut_event_status_do);
                appointmentView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        submitAppointment();
                    }
                });
            }
        }
    }

    private void initEvent(){
        eventName.setText(((null==event.publisher)?"":event.publisher) + " " + ((null==event.role)?"":event.role));
        availableAmount.setText(event.available);
        eventTitle.setText(event.title);
        eventAction.setText(event.action);
        eventDetail.setText(event.detail);
        eventValue.setText(event.value);

        appointmentView.setVisibility(View.GONE);
        /*
        if(null == event.status || event.status.length() == 0){
            submitAppointmentImage.setImageResource(R.drawable.red_square);
            appointmentStatusView.setText(R.string.walnut_event_status_do);
        }
        else if(event.status.equals(APPOINTMENT_STATUS_DONE)){
            submitAppointmentImage.setImageResource(R.drawable.grey_square);
            appointmentStatusView.setText(R.string.walnut_event_status_done);
            appointmentView.setOnClickListener(null);
        }
        else {
            submitAppointmentImage.setImageResource(R.drawable.grey_square);
            appointmentStatusView.setText(R.string.walnut_event_status_waiting);
            appointmentView.setOnClickListener(null);
        }
        */
        imageLoader.loadImage(event.AD, eventImage, false, false);
    }

    private void reservation() {
        submitAppointmentImage.setImageResource(R.drawable.grey_square);
        appointmentStatusView.setText(R.string.walnut_event_status_waiting);
        appointmentView.setOnClickListener(null);
        Toast.makeText(this, this.getString(R.string.walnut_reservation_success), Toast.LENGTH_LONG).show();
    }

    /**
     * Response to user's appointment
     */
    private void submitAppointment(){
        //TODO: submit a appointment with publisher
        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        int userId = PrefUtils.getUserId(this);
        serviceHandler.reservationEvent(restAdapter, event, userId, notifyHandler, RESERVATION_EVENT_INFO);
    }

    private static class HeroNotifyHandler extends WalnutBaseNofityHandler<ChampionActivity, HeroInfo>{
        public HeroNotifyHandler(ChampionActivity championActivity) {
            super(championActivity);
        }

        @Override
        public void handleOtherMessage(Message msg) {
            Bundle bundle = msg.getData();
            if(null == bundle.getString(RetrofitNetworkService.RESULT_ERROR)){
                Toast.makeText(get(), R.string.walnut_deal_timeout, Toast.LENGTH_SHORT).show();
                return;
            }
            if(!bundle.getString(RetrofitNetworkService.RESULT_ERROR).equals(RetrofitNetworkService.RESULT_ERROR_NONE)){
                get().heroProgress.setVisibility(View.GONE);
                Toast.makeText(get(), "Failed to get data", Toast.LENGTH_SHORT).show();
                return;
            }
            if(msg.what == GET_HERO_INFO){
                Object[] info = (Object[])bundle.get(RetrofitNetworkService.RESULT_DATA);
                if(null != info && info.length > 0) {
                    HeroInfo inf = (HeroInfo)info[0];
                    if(null != inf) {
                        ImageAndAnimateUtils.showPersonHeaderPortait(get().imageLoader, get().eventHeroHeadImage, inf.headPortrait);
                        get().eventHeroSkill.setText(inf.magics);
                        get().eventHeroIntroduction.setText(inf.brief);
                    }
                    else {
                        get().imageLoader.loadImageByResources(R.drawable.walnut_logo, get().eventHeroHeadImage, true, false);
                    }
                }
                get().heroProgress.setVisibility(View.GONE);
            }
            else if(msg.what == GET_EVENT_INFO){
                get().event =
                        (WalnutMainEvent)bundle.get(RetrofitNetworkService.RESULT_DATA);
                get().initEvent();
            }
            else if (msg.what == RESERVATION_EVENT_INFO) {
                String ok = (String)bundle.get(RetrofitNetworkService.RESULT_DATA);
                // 判断，然后调用对应的方法改变一下对应控件的状态
                if ("ok".equals(ok)) {
                    get().reservation();
                }
                else {
                    Toast.makeText(get(), get().getString(R.string.walnut_reservation_fail), Toast.LENGTH_LONG).show();
                }
            }
            else if (msg.what == GET_BOOKING_STATE) {
                String state = (String)bundle.get(RetrofitNetworkService.RESULT_DATA);
                get().changeState(state);
            }
            super.handleOtherMessage(msg);
        }
    }
}
